﻿using SQLite;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace CommDao
{
    public abstract class CommDao<T> where T : new()
    {
        protected string path;
        SQLiteConnection db = null;

        public CommDao()
        {
        }

        public CommDao(string path)
        {
            this.path = Path.GetFullPath(path);

            FileInfo info = new FileInfo(path);
            if (!info.Directory.Exists)
            {
                info.Directory.Create();
            }

            try
            {
                db = Connect();
                db.CreateTable<T>();
            }
            finally
            {
                DisConnect();
            }
        }

        public void Insert(T t)
        {
            try
            {
                db = Connect();
                db.Insert(t);
            } finally
            {
                db.Close();
            }
        }

        public List<T> Select()
        {
            try
            {
                db = Connect();
                return db.Table<T>().ToList();
            }
            finally
            {
                db.Close();
            }
        }

        public void Delete(T t)
        {
            try
            {
                db = Connect();
                db.Delete(t);
            }
            finally
            {
                db.Close();
            }
        }

        public void Update(T t)
        {
            try
            {
                db = Connect();
                db.Update(t);
            }
            finally
            {
                db.Close();
            }
        }

        protected SQLiteConnection Connect()
        {
            return new SQLiteConnection(path);
        }

        protected void DisConnect()
        {
            db.Close();
        }
    }
}